1
從直接 API 呼叫到 LangChain 抽象
AI010Lesson 5
00:00

超越原始請求

當開始使用大型語言模型(LLMs)時,開發者通常會使用直接的 API 呼叫(例如 OpenAI 的 Python 庫)來發送提示並接收完成結果。雖然這方法可行,但隨著應用程式規模擴大,這種方式會變得難以管理。

狀態無關性的問題

大型語言模型本質上是 無狀態的。每次您發送訊息時,模型都會『忘記』你是誰以及之前說過什麼。每一次互動都是一張白紙。為了維持對話,您必須每次都手動將完整的歷史記錄傳回給模型。

LangChain 的解決方案

LangChain 引入了 ChatOpenAI 模型包裝器。這不僅僅是為了包裝而包裝——它正是實現 模組化 的基礎。透過抽象模型呼叫,我們後續可以輕鬆切換模型、注入記憶體,並使用模板,而無需重寫整個代碼庫。

海盜情境示例
想像一封用「海盜式」俚語撰寫的客戶郵件。若要將其轉譯為正式的企業回覆,直接的 API 呼叫需要硬編碼指令。使用 LangChain 時,我們透過抽象,將「風格」(海盜風 vs. 正式)與「內容」(郵件本身)分離。
main.py
TERMINALbash — 80x24
> Ready. Click "Run" to execute.
>
Question 1
Why do we say LLMs are "stateless"?
They do not have access to the internet.
They cannot generate the same response twice.
They do not inherently remember previous messages in a conversation.
They are only capable of processing text, not data states.
Challenge: Initialize ChatOpenAI
Solve the problem below.
You are building a creative writing assistant and need to initialize your first LangChain model.

Your task is to create a ChatOpenAI instance named my_llm with a temperature of 0.7 to allow for more creative (non-deterministic) responses.
Task
Write the Python code to import and initialize the model.
Solution:
from langchain_openai import ChatOpenAI
my_llm = ChatOpenAI(temperature=0.7)